package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021-8-25.<br><br>
 *
 * 中等：删除排序链表中的重复元素 II
 */
public class Topic82 {

    public static void main(String[] args) {
        Topic82 instance = new Topic82();

        int[] array = new int[] {1,2,3,3,4,4,5};
        ListNode head = Util.createList(array);
        Util.printList(instance.deleteDuplicates(head));

        array = new int[] {1,1,1,2,3};
        head = Util.createList(array);
        Util.printList(instance.deleteDuplicates(head));
    }

    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) {
            return null;
        }

        if(head.next != null && head.val == head.next.val) {
            while (head.next != null && head.val == head.next.val) {
                head = head.next;
            }

            return deleteDuplicates(head.next);
        }
        else {
            head.next = deleteDuplicates(head.next);
        }

        return head;
    }

    public ListNode deleteDuplicates2(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }

        ListNode start = new ListNode(0);
        start.next = head;
        ListNode pre = start;

        while (pre.next != null && pre.next.next != null) {
            if(pre.next.val == pre.next.next.val) {
                int value = pre.next.val;
                while (pre.next != null && pre.next.val == value) {
                    pre.next = pre.next.next;
                }
            }
            else {
                pre = pre.next;
            }
        }

        return start.next;
    }
}
